All files / web/src/app/api/worksheets/share/[id] route.ts

0% Statements 0/67
0% Branches 0/1
0% Functions 0/1
0% Lines 0/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                                                                                                                       
import { eq, sql } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { db } from '@/db'
import { worksheetShares } from '@/db/schema'
import { isValidShareId } from '@/lib/generateShareId'
import { parseAdditionConfig } from '@/app/create/worksheets/config-schemas'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * GET /api/worksheets/share/[id]
 *
 * Retrieve a shared worksheet configuration by ID
 * Increments view counter on each access
 *
 * Response:
 * {
 *   id: 'abc123X',
 *   worksheetType: 'addition',
 *   config: { ...worksheet config object },
 *   createdAt: '2025-01-01T00:00:00.000Z',
 *   views: 42,
 *   title: 'Optional title'
 * }
 */
export const GET = withAuth(async (_request, { params }) => {
  try {
    const { id } = (await params) as { id: string }

    // Validate ID format
    if (!isValidShareId(id)) {
      return NextResponse.json({ error: 'Invalid share ID format' }, { status: 400 })
    }

    // Fetch share record
    const share = await db.query.worksheetShares.findFirst({
      where: eq(worksheetShares.id, id),
    })

    if (!share) {
      return NextResponse.json({ error: 'Share not found' }, { status: 404 })
    }

    // Increment view counter
    await db
      .update(worksheetShares)
      .set({
        views: sql`${worksheetShares.views} + 1`,
      })
      .where(eq(worksheetShares.id, id))

    // Parse and validate config (auto-migrates to latest version)
    // This ensures shared configs are validated just like user session configs
    const config = parseAdditionConfig(share.config)

    return NextResponse.json({
      id: share.id,
      worksheetType: share.worksheetType,
      config,
      createdAt: share.createdAt.toISOString(),
      views: share.views + 1, // Return incremented count
      title: share.title,
    })
  } catch (error) {
    console.error('Error fetching worksheet share:', error)
    return NextResponse.json({ error: 'Failed to fetch share' }, { status: 500 })
  }
})